<template lang="pug">
Editor(v-model="content" :init="editorProps || setting ")
</template>
<script>
  import Editor from '@tinymce/tinymce-vue'
  import tinymce from 'tinymce/tinymce'
  import 'tinymce/themes/silver/theme'
  // 需要配置tinymce的根路径
  window.tinymce.baseURL = '/tinymce'
  export default {
    components: {
      Editor,
    },
    props: {
      editorProps: {
        type: Object,
        default() {
          return null
        },
      },
      width: {
        type: Number,
        default: 720,
      },
      height: {
        type: Number,
        default: 500,
      },
      imagesUploadHandler: {
        type: Function,
        default: null,
      },
      // 使用imageUploadURL的话服务器返回的内容中必须包含“location”属性的JSON对象
      // 如：{ location : '/uploaded/image/path/image.png' } ，否则图片还是会转换成base64格式
      imageUploadURL: {
        type: String,
        default: null,
      },
      // 服务器上传路径，需要配合imagesUploadHandler一起使用
      serverUploadPath: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        content: '',
        setting: {
          width: this.width,
          height: this.height,
          language_url: '/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          skin_url: '/tinymce/skins/ui/oxide',
          menubar: 'file edit view insert format tools table help', //帮助栏
          statusbar: false,
          convert_urls: false,
          toolbar_mode: 'sliding',
          images_upload_url: this.imageUploadURL,
          images_upload_handler: this.imagesUploadHandler || this.imgUpload,
          //插件栏  主要是一些图片、文件类的工具
          plugins:
            'print preview paste importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media  codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap quickbars emoticons',
          //基本工具栏 左对齐右对齐，字体大小等
          toolbar:
            'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | forecolor backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | fullscreen  preview save print | insertfile image media pageembed  link anchor codesample | a11ycheck ltr rtl | showcomments addcomment',
          init_instance_callback: (editor) => {
            return editor
          },
          image_caption: true,
          autosave_ask_before_unload: true,
          autosave_interval: '30s',
          autosave_restore_when_empty: false,
          autosave_retention: '2m',
          autosave_prefix: '{path}{query}-{id}-',
          contextmenu: 'link image imagetools table',
        },
      }
    },
    mounted() {
      tinymce.init(this.editorProps || this.setting)
      this.content = ''
    },
    methods: {
      imgUpload(blobInfo, success, failure, progress) {
        if (!this.serverUploadPath) throw new Error('缺少文件上传路径')
        let xhr, formData
        let that = this
        xhr = new XMLHttpRequest()
        xhr.withCredentials = false
        xhr.open('POST', this.serverUploadPath)
        this.$emit('imgUploading')
        xhr.upload.onprogress = function (e) {
          progress((e.loaded / e.total) * (100 - 1))
        }

        xhr.onload = function () {
          let json

          if (xhr.status === 403) {
            failure('HTTP Error: ' + xhr.status, { remove: true })
            return
          }

          if (xhr.status < 200 || xhr.status >= 300) {
            failure('HTTP Error: ' + xhr.status)
            return
          }

          json = JSON.parse(xhr.responseText)

          if (!json || typeof json.url !== 'string') {
            failure('Invalid JSON: ' + xhr.responseText)
            return
          }

          let timer = setInterval(() => {
            if (that.CheckImgExists(json.url)) {
              progress(100)
              that.$emit('imgUploaded')
              success(json.url)
              clearInterval(timer)
            }
          }, 500)
        }

        xhr.onerror = function () {
          failure(
            'Image upload failed due to a XHR Transport error. Code: ' +
              xhr.status
          )
        }

        formData = new FormData()
        formData.append('file', blobInfo.blob(), blobInfo.filename())

        xhr.send(formData)
      },
      CheckImgExists(imgurl) {
        let ImgObj = new Image() //判断图片是否存在
        ImgObj.src = imgurl
        //存在图片
        if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
          return true
        } else {
          return false
        }
      },
    },
  }
</script>
<style lang="less" scoped></style>
